package shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.mapper.SysSupplierMapper;
import shop.pojo.StorageRecord;
import shop.pojo.Supplier;
import shop.pojo.SysRole;
import shop.pojo.SysUser;
import shop.service.StorageRecordService;
import shop.service.SysSupplierService;
import shop.utils.Constants;
import shop.utils.OssUtil;
import shop.utils.PageSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/storageRecord")
public class StorageRecordController {


    @Autowired
    StorageRecordService storageRecordService;

    @Autowired
    SysSupplierService sysSupplierService;

    @RequestMapping("/list")
    public String getUserList(Model model, String queryGoodsName, String querySupplierId,String querypayStatus, @RequestParam(defaultValue = "1") Integer pageIndex){
        List<StorageRecord> storageRecord=null;
        try {
            //设置页面展示条数
            int pageSize = Constants.pageSize;
            System.out.println(pageSize+"展示条数");
            //总条数量
            Integer totalCount =storageRecordService.getStorageRecordCount(queryGoodsName,querySupplierId,querypayStatus);
            //总页数
            PageSupport pages =new PageSupport();
            pages.setTotalCount(totalCount);
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            int totalPageCount =pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex>totalPageCount){
                pageIndex=totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            storageRecord=storageRecordService.getStorageRecordList(queryGoodsName,querySupplierId,querypayStatus,pageIndex,pageSize);
            model.addAttribute("storageRecord",storageRecord);
            List<StorageRecord> storageRecordList=null;
            //roleList=sysSupplierService.getSupplierList();
            model.addAttribute("storageRecordList",storageRecordList);
            System.out.println(storageRecordList);
            model.addAttribute("queryGoodsName",queryGoodsName);
            model.addAttribute("querySupplierId",querySupplierId);
            model.addAttribute("querypayStatus",querypayStatus);
            model.addAttribute("totalPageCount",totalPageCount);
            System.out.println(totalPageCount);
            model.addAttribute("totalCount",totalCount);
            System.out.println(totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            System.out.println(pageIndex);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "storageRecord/list";
    }

    //查询详情
    @GetMapping("/view/{storageRecordId}/{supName}")
    public String userView(@PathVariable Integer storageRecordId, Model model,@PathVariable String supName){
        StorageRecord storageRecord = storageRecordService.getStorageRecordDetail(storageRecordId);
        model.addAttribute(supName);
        model.addAttribute(storageRecord);
        return "storageRecord/view";
    }

    //去修改页面
    @GetMapping("/toUpdate/{storageRecordId}")
    public String toUpdate(@PathVariable Integer storageRecordId,Model model){
        StorageRecord storageRecord = storageRecordService.getStorageRecordDetail(storageRecordId);
        List<Supplier> supplier = sysSupplierService.getSupnameAndId();
        model.addAttribute(storageRecord);
        model.addAttribute(supplier);
        return "storageRecord/update";
    }

    //修改
    @PostMapping("/update")
    public String toUserUpdate(StorageRecord storageRecord, HttpSession session, HttpServletRequest request){
        Long id = ((SysUser) session.getAttribute(Constants.USER_SESSION)).getId();

        if(request.getParameter("createdtime")==""||request.getParameter("createdtime")==null){
            storageRecord.setCreatedtime(new Date());
        }
        storageRecord = storageRecordService.getStorageRecordDetail(Integer.valueOf(request.getParameter("id")));
        storageRecord.setGoodsname(request.getParameter("goodsName"));
        storageRecord.setGoodsunit(request.getParameter("goodsUnit"));
        try {
            String goodsCountStr = request.getParameter("goodsCount");
            if (goodsCountStr != null && !goodsCountStr.isEmpty()) {
                storageRecord.setGoodscount(new BigDecimal(goodsCountStr));
            } else {
                // 处理 goodsCount 为 null 或空字符串的情况
            }

            String totalAmountStr = request.getParameter("totalAmount");
            if (totalAmountStr != null && !totalAmountStr.isEmpty()) {
                storageRecord.setTotalamount(new BigDecimal(totalAmountStr));
            } else {
                // 处理 totalAmount 为 null 或空字符串的情况
            }
        } catch (NumberFormatException e) {
            // 处理解析异常，例如返回错误消息或记录日志
            // 在这个特定情况下，由于我们已经直接使用了 BigDecimal 构造函数，
            // 这个异常应该不会再被抛出，除非输入的字符串不是一个有效的数字表示
            e.printStackTrace();
        }
        storageRecord.setSupplierid((long) Integer.parseInt(request.getParameter("supplierId")));
        storageRecord.setPaystatus(Integer.valueOf(request.getParameter("payStatus")));
        if(storageRecordService.update(storageRecord)>0){
            return "redirect:/storageRecord/list";
        }
        return "storageRecord/update";
    }

    @GetMapping("/delete")
    public ResponseEntity<Map<String, String>> deleteUser(@RequestParam("method") String method,
                                                          @RequestParam("storageRecordId") Integer storageRecordId) {
        Map<String, String> responseMap = new HashMap<>();

        System.out.println(method);
        System.out.println(storageRecordId);
        if ("deleteById".equals(method)) {

            // 检查用户是否存在

                // 删除用户
                Integer isDeleted = storageRecordService.deleteStorageRecordById(storageRecordId);
                if (isDeleted>0) {
                    responseMap.put("delResult", "true");
                } else {
                    responseMap.put("delResult", "false"); // 假设这里表示发生了某种错误，而不是用户不存在
                }
        } else {
            // 未知的方法，返回错误
            responseMap.put("delResult", "unknown_method");
        }
        return new ResponseEntity<>(responseMap, HttpStatus.OK);
    }


    @GetMapping("/toAdd")
    public String toAdd(HttpServletRequest request){
        return "storageRecord/add";
    }


    //用户添加
    @PostMapping("/add")
    public String add(StorageRecord storageRecord, HttpSession session,Model model,HttpServletRequest request
    ) throws IOException {
        SysUser create =(SysUser) session.getAttribute(Constants.USER_SESSION);
        System.out.println(create);
        storageRecord.setUpdateduserid(create.getId());
        storageRecord.setSrcode(request.getParameter("srCode"));

        storageRecord.setGoodsname(request.getParameter("goodsName"));
        try {
            String goodsCountStr = request.getParameter("goodsCount");
            if (goodsCountStr != null && !goodsCountStr.isEmpty()) {
                storageRecord.setGoodscount(new BigDecimal(goodsCountStr));
            } else {
                // 处理 goodsCount 为 null 或空字符串的情况
            }

            String totalAmountStr = request.getParameter("totalAmount");
            if (totalAmountStr != null && !totalAmountStr.isEmpty()) {
                storageRecord.setTotalamount(new BigDecimal(totalAmountStr));
            } else {
                // 处理 totalAmount 为 null 或空字符串的情况
            }
        } catch (NumberFormatException e) {
            // 处理解析异常，例如返回错误消息或记录日志
            // 在这个特定情况下，由于我们已经直接使用了 BigDecimal 构造函数，
            // 这个异常应该不会再被抛出，除非输入的字符串不是一个有效的数字表示
            e.printStackTrace();
        }
        storageRecord.setGoodsunit(request.getParameter("goodsUnit"));
        storageRecord.setSupplierid(Long.valueOf(request.getParameter("supplierId")));
        storageRecord.setPaystatus(Integer.valueOf(request.getParameter("payStatus")));
        storageRecord.setCreatedtime(new Date());
        if(storageRecordService.add(storageRecord)){
            return "redirect:/storageRecord/list";
        }else {
            return "storageRecord/add";
        }

    }


}
